<template>
<!--  -->
<!-- 此页面为自定义组件：更换头像弹窗 -->
<!--  -->
    <div>
        <!-- 更换头像弹窗 -->
        <Dialog
          :show="dialogConfig.show"
          :title="dialogConfig.title"
          :buttons="dialogConfig.buttons"
          :showCancel="false"
          width="400px"
          @close="dialogConfig.show = false"
        >
          <!-- @submit.prevent: 用于阻止表单的默认提交行为 -->
          <el-form ref="formDataRef" :model="formData" label-width="80px" @submit.prevent>
              
              <!-- 用户昵称显示 -->
              <el-form-item label="昵称">
                  {{ formData.nickName }}
              </el-form-item>

              <!-- 用户头像显示 通过v-model接收子组件AvatarUpload.vue传递参数 -- uploadImage方法中 -->
              <el-form-item label="头像">
                  <AvatarUpload v-model="formData.avatar"></AvatarUpload>           
              </el-form-item>

          </el-form>
        </Dialog>
    </div>
</template>

<script setup>
import { ref, reactive, getCurrentInstance, nextTick, onMounted } from "vue";
import AvatarUpload from "@/components/AvatarUpload.vue";     //引入自定义的组件
const { proxy } = getCurrentInstance();

const formData = ref({});
const formDataRef = ref();

const api = {
    updateUserAvatar: "/updateUserAvatar",   //更换头像的请求地址
}
// 弹窗定义
const dialogConfig = ref({
    show: false,   //false为关闭弹窗
    title: "更换头像",
    buttons: [
        {
          type: "primary",
          text: "确定",
          click: (e) => {
            submitForm();
          },
        },
    ],
});

//打开弹窗  由父组件Framework.vue的updateAvatar方法调用
const show = (data) => {
  formData.value = Object.assign({}, data);
  formData.value.avatar = { userId: data.userId, qqAvatar: data.avatar };
  console.log("UpdateAvatar.vue----" + formData.value.avatar);
  dialogConfig.value.show = true;
}
defineExpose({ show });    //是Vue3中的一个新特性,它允许组件将其内部的数据和方法暴露给父组件


const emit = defineEmits();     //子组件通过触发父组件的事件，并将参数传递到父组件
//弹窗确定按钮
const submitForm = async () => {
  console.log("UpdateAvatar.vue -- submitForm");
  if (!(formData.value.avatar instanceof File)) { //判断是否为文件  （如果未选择新头像，则不是文件）
    dialogConfig.value.show = false;      //未选择头像，直接关闭弹窗
    return;
  }
  console.log("UpdateAvatar.vue -- submitForm 已选文件 -- " + formData.value.avatar);
  //发送更换头像的请求
  let result = await proxy.Request({
    url: api.updateUserAvatar,
    params: {
      avatar: formData.value.avatar,
    },
  });
  if (!result) {
    console.log("UpdateAvatar.vue -- 86");
    return;
  }
  dialogConfig.value.show = false;
  const cookeUserInfo = proxy.VueCookies.get("userInfo");
  delete cookeUserInfo.avatar;                       //因为更换了头像，所以删除cookie原先存储的头像
  proxy.VueCookies.set("userInfo", cookeUserInfo, 0);//重新设置cookie，0为关闭浏览器删除
  emit("updateAvatar");          //子组件通过触发父组件的事件，并将参数传递到父组件
}

</script>

<style>

</style>